
#import "ChapterViewController.h"

#import "Chapter.h"
#import "Ingredient.h"

#import "InstructionsViewController.h"
#import "TypeSelectionViewController.h"
#import "RecipePhotoViewController.h"
#import "IngredientDetailViewController.h"


///////////////////////////////////////////////////////////
//  Descriptions
//  Object->Responder->viewController->tableViewController->ChapterViewController
//  
//  Synthesize the getters/setters
//
//  Instance Methods:
//     (IBAction) photoTapped;
//
//  Override the super class viewController:
//     (void) viewDidLoad;
//     (void) viewWillAppear:(BOOL) animated
//     (void) viewDidUnload;
//     (void) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation *);
//
//  UITextField Delegate interface:
//     (void) setEditing:(BOOL): animated:(BOOL);
//     (BOOL) textFieldShouldEndEditing:(UITextField *);
//     (BOOL) textFieldShouldReturn:(UITextField *);
//     
//  UITableView Datasource Delegate protocol
//     (int) numberOfSectionsInTableView:(UITableView *);
//     (NSString *) tableView:titleForHeaderInSection:(NSInteger);
//     (int) tableView:numberOfRowsInSection:(int); 
//     (UITableViewCell *) tableView:cellForRowAtIndexPath:
//     (void) tableView:commitEditingStyle:(UITableViewCellEditingStyle):forRowAtIndexPath:
//     (BOOL) tableView:canMoveRowAtIndexPath:
//     (void) tableView:moveRowAtIndexPath:toIndexPath:
//
//  UITableView Delegate protocol:
//     (void) tableView:willSelectRowAtIndexPath:(NSIndexPath *);
//     (void) tableView:didSelectRowAtIndexPath:(NSIndexPath *);
//     (UITableViewCellEditingStyle) tableView:editingStyleForRowAtIndexPath:
//     (NSIndexPath *) tableView:
//                     targetIndexPathForMoveFromRowAtIndexPath:
//                     toProposedIndexPath:;
//
//  UINavigationController Delegate interface:
//     ...
//
//
//  UIImagePickerController Delegate interface:
//     (void) imagePickerController:didFinishPickingImage:(UIImage *) editingInfo:(NSDictionary *);
//     (void) imagePickerControllerDidCancel:(UIImagePickerController *);
//
//  ChapterViewController private methods:
//     (void) updatePhotoButton;
///////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////
// Chapter View Controller private methods definition
/////////////////////////////////////////////////////////////
@interface ChapterViewController (PrivateMethods)
-(void)updatePhotoButton;
@end




/////////////////////////////////////////////////////////////
// Chapter View Controller class implementation
// obj->responder->viewController->tableViewController<delegates>
// 1) dataSource
// 2) tableView
// 3) textField 
// 4) imagePickerController
// 5) navigationController: not implementated
//    -(void) navigationController:willShowViewController:animated
//    -(void) navigationController:didShowViewController:animated
/////////////////////////////////////////////////////////////
@implementation ChapterViewController

@synthesize chapter=m_Chapter;
@synthesize chapterContents=m_ChapterContents;

@synthesize tableHeaderView=m_TableHeaderView;
@synthesize photoButton=m_PhotoButton;
@synthesize nameTextField=m_NameTextField;
@synthesize overviewTextField=m_OverviewTextField;
@synthesize prepTimeTextField=m_PrepTimeTextField;


#define TYPE_SECTION 0
#define INGREDIENTS_SECTION 1
#define INSTRUCTIONS_SECTION 2


#pragma mark -
#pragma mark Photo
/////////////////////////////////////////////////////////////
-(IBAction) photoTapped {

   NSLog(@"-------------> ChapterViewController::photoTapped");
   // If in editing state, then display an image picker; if not, create and push a photo view controller.
   if( self.editing ) {
      UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
      imagePicker.delegate = self;
      [self presentModalViewController:imagePicker animated:YES];
      [imagePicker release];
   } 
   else {   

      /**
       * Create RecipePhotoViewController, set properites and 
       * push it on the viewController stack
       */
      RecipePhotoViewController *recipePhotoViewController = [[RecipePhotoViewController alloc] init];
      recipePhotoViewController.hidesBottomBarWhenPushed = YES;
      recipePhotoViewController.recipe = m_Chapter;
      [self.navigationController pushViewController:recipePhotoViewController 
                                           animated:YES];
      [recipePhotoViewController release];
   }
}


#pragma mark -
#pragma mark View controller

/////////////////////////////////////////////////////////////
//  1) Setup the top part on the table view, DetailHeaderView
-(void)viewDidLoad {
   
  /**
   * set naviagationItem on the top right
   */
   self.navigationItem.rightBarButtonItem = self.editButtonItem;
   
   /**
    * Create and set the chapter header from
    * the pre-definted nib file (DetailHeadView.xib):
    * photo, Chapter name, brif description.
    */
   if( m_TableHeaderView == nil ) {
     /**
      * get the nib file from the application resource directory
      * DetailHeaderView.xib defines relation btw all view related instance
      * variables and their objects.
      */
       [[NSBundle mainBundle] loadNibNamed:@"DetailHeaderView" 
                                     owner:self 
                                   options:nil];

       /**
	     * tableViewController has tableView.
	     * tableHeaderView instance variable points
	     * to the view object defined in the xib.
	     */
       [[self tableView] setTableHeaderView: m_TableHeaderView];
       [[self tableView] setAllowsSelectionDuringEditing: YES];
   }


}

/////////////////////////////////////////////////////////////
//  1) Config views (Main View: Detailed Header View
//     and its subViews text fields, button.
// 
//  2) Model (data)
//     
//
-(void)viewWillAppear:(BOOL)animated {
   
   [super viewWillAppear:animated];

   /** 
    * Config phone button for the chapter view (not needed)
    */	
   [[self photoButton] setImage:m_Chapter.thumbnailImage 
                forState:UIControlStateNormal];

   /**
    * Set chapter name and other sections
    * Set UIText objects (loaded from nib) text property
    */
   self.navigationItem.title = m_Chapter.name;
   m_NameTextField.text = m_Chapter.name;    
   m_OverviewTextField.text = m_Chapter.overview;    
   m_PrepTimeTextField.text = m_Chapter.prepTime;    

   [self updatePhotoButton];


   id<UITableViewDelegate> del = [[self tableView] delegate];
   NSLog(@"------> tableView delegate: %p", del);

   id<UITableViewDataSource> dataSrc = [[self tableView] delegate];
   NSLog(@"------> tableView data source: %p", dataSrc);

   NSLog(@"------> self: %p", self);
   /*
    Create a mutable array that contains the chapter's contents
    ordered by displayOrder.
    The table view uses this array to display the contents.
    Core Data relationships are represented by sets, so have no inherent order. 
    Order is "imposed" using the displayOrder attribute, but it would be 
    inefficient to create and sort a new array each time the ingredients 
    section had to be laid out or updated.
    */
   NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"displayOrder" 
                                                                  ascending:YES];
   NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor 
                                                         count:1];
   
   /**
    * get all chapterContents data(set) from the chapter instance
    * and update the tableView.
    */
   NSMutableArray *sortedIngredients = [[NSMutableArray alloc] initWithArray:[m_Chapter.ingredients allObjects]];
   [sortedIngredients sortUsingDescriptors:sortDescriptors];

   /**
    * assign the sorted ingredient data from the chapter
    * to the controller's chapterContents
    */
   m_ChapterContents = sortedIngredients;

   [sortDescriptor release];
   [sortDescriptors release];
   [sortedIngredients release];
   
   /**
    * Update chapter type and chapterContents on return.
    */
   [[self tableView] reloadData]; 
}

/////////////////////////////////////////////////////////////
-(void)viewDidUnload {
   self.tableHeaderView = nil;
   self.photoButton = nil;
   self.nameTextField = nil;
   self.overviewTextField = nil;
   self.prepTimeTextField = nil;
   [super viewDidUnload];
}

/////////////////////////////////////////////////////////////
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
   return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}






#pragma mark -
#pragma mark Editing

/////////////////////////////////////////////////////////////
// UITextFieldDelegate implementation
// 1) -(void)setEditing:animation
// 2) -(BOOL)textFieldShouldEndEditing
// 3) -(BOOL)textFieldShouldReturn
/////////////////////////////////////////////////////////////
-(void)setEditing:(BOOL)editing 
         animated:(BOOL)animated {
   
   [super setEditing:editing 
            animated:animated];
   
   [self updatePhotoButton];

   m_NameTextField.enabled = editing;
   m_OverviewTextField.enabled = editing;
   m_PrepTimeTextField.enabled = editing;

   [self.navigationItem setHidesBackButton:editing 
                                  animated:YES];
   

   [self.tableView beginUpdates];
   
   NSUInteger ingredientsCount = [m_Chapter.ingredients count];
   
   NSArray *ingredientsInsertIndexPath = [NSArray arrayWithObject:
                                                     [NSIndexPath indexPathForRow:ingredientsCount
                                                                        inSection:INGREDIENTS_SECTION]];
   
   if( editing ) {
      [self.tableView insertRowsAtIndexPaths:ingredientsInsertIndexPath 
                            withRowAnimation:UITableViewRowAnimationTop];

      m_OverviewTextField.placeholder = @"Overview";
   } 
   else {
      [self.tableView deleteRowsAtIndexPaths:ingredientsInsertIndexPath 
                             withRowAnimation:UITableViewRowAnimationTop];

      m_OverviewTextField.placeholder = @"";
   }
   
   [self.tableView endUpdates];
   
   /*
    If editing is finished, save the managed object context.
    */
   if( !editing ) {
      NSManagedObjectContext *context = m_Chapter.managedObjectContext;
      NSError *error = nil;
      if (![context save:&error]) {
         /*
          Replace this implementation with code to handle the error appropriately.
          
          abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
          */
         NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
         abort();
      }
   }
}

/////////////////////////////////////////////////////////////
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField {
   
   if (textField == m_NameTextField) {
      m_Chapter.name = m_NameTextField.text;
      self.navigationItem.title = m_Chapter.name;
   }
   else if (textField == m_OverviewTextField) {
      m_Chapter.overview = m_OverviewTextField.text;
   }
   else if (textField == m_PrepTimeTextField) {
      m_Chapter.prepTime = m_PrepTimeTextField.text;
   }
   return YES;
}

/////////////////////////////////////////////////////////////
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
   [textField resignFirstResponder];
   return YES;
}





#pragma mark -
#pragma mark UITableView Delegate/Datasource
/////////////////////////////////////////////////////////////
// TableView data source delegate implementation
//    (NSInteger) numberOfSectionInTableView:
//    (NSString *) tableView:titleForHeaderInSection:
//    ...
/////////////////////////////////////////////////////////////
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return 4;
}

/////////////////////////////////////////////////////////////
-(NSString *) tableView:(UITableView *)tableView 
titleForHeaderInSection:(NSInteger)section {
   NSString *title = nil;
   // Return a title or nil as appropriate for the section.
   switch (section) {
       case TYPE_SECTION:
           title = @"Category";
           break;
       case INGREDIENTS_SECTION:
           title = @"Description?";
           break;
       default:
           break;
   }
   return title;;
}

/////////////////////////////////////////////////////////////
-(NSInteger)tableView:(UITableView *)tableView 
numberOfRowsInSection:(NSInteger)section {
   NSInteger rows = 0;
   
   /*
    The number of rows depends on the section.
    In the case of ingredients, if editing, add a row in editing mode to present an "Add Ingredient" cell.
    */
   switch (section) {
       case TYPE_SECTION:
       case INSTRUCTIONS_SECTION:
           rows = 1;
           break;

       case INGREDIENTS_SECTION:
           rows = [m_Chapter.ingredients count];
           if (self.editing) {
               rows++;
           }
           break;

      default:
           break;
   }

   return rows;
}

/////////////////////////////////////////////////////////////
// Create a tableView cell for different table sections
-(UITableViewCell *)tableView:(UITableView *)tableView 
        cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   UITableViewCell *cell = nil;
   
    // For the Ingredients section, if necessary create a new cell and configure it with an additional label for the amount.  Give the cell a different identifier from that used for cells in other sections so that it can be dequeued separately.
   if (indexPath.section == INGREDIENTS_SECTION) {

      NSUInteger ingredientCount = [m_Chapter.ingredients count];
      NSInteger row = indexPath.row;
      
      if( indexPath.row < ingredientCount ) {
           // If the row is within the range of the number of chapterContents for the current chapter, then configure the cell to show the ingredient name and amount.
         static NSString *ChapterContentsCellIdentifier = @"ChapterContentsCell";
         
         cell = [tableView dequeueReusableCellWithIdentifier:ChapterContentsCellIdentifier];
         
         if (cell == nil) {
             // Create a cell to display an ingredient.
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                           reuseIdentifier:ChapterContentsCellIdentifier] autorelease];

            cell.accessoryType = UITableViewCellAccessoryNone;
         }
         
         Ingredient *ingredient = [m_ChapterContents objectAtIndex:row];
         cell.textLabel.text = ingredient.name;
         cell.detailTextLabel.text = ingredient.amount;
       } 

       else {
           // If the row is outside the range, it's the row that was added to allow insertion (see tableView:numberOfRowsInSection:) so give it an appropriate label.
         static NSString *AddIngredientCellIdentifier = @"AddIngredientCell";
         
         cell = [tableView dequeueReusableCellWithIdentifier:AddIngredientCellIdentifier];
         if (cell == nil) {
             // Create a cell to display "Add Ingredient".
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                           reuseIdentifier:AddIngredientCellIdentifier] autorelease];

            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
         }

         cell.textLabel.text = @"Add Ingredient";
       }
   } 
   else {
       // If necessary create a new cell and configure 
       // it appropriately for the section.  Give the cell 
       // a different identifier from that used for cells in 
       // the ChapterContents section so that 
       // it can be dequeued separately.
       static NSString *MyIdentifier = @"GenericCell";
       
       cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
       if (cell == nil) {
           cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                          reuseIdentifier:MyIdentifier] autorelease];

           cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
       }
       
       NSString *text = nil;
       
       switch (indexPath.section) {
           case TYPE_SECTION: // type -- should be selectable -> checkbox
               text = [m_Chapter.type valueForKey:@"name"];
               cell.accessoryType = UITableViewCellAccessoryNone;
               cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
               break;

           case INSTRUCTIONS_SECTION: // instructions
               text = @"Instructions";
               cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
               cell.editingAccessoryType = UITableViewCellAccessoryNone;
               break;

           default:
               break;
       }
       
       cell.textLabel.text = text;
   }

   return cell;
}



#pragma mark -
#pragma mark Editing rows
/////////////////////////////////////////////////////////////
// TableView delegate implementation
/////////////////////////////////////////////////////////////
-(NSIndexPath *)tableView:(UITableView *)tableView 
 willSelectRowAtIndexPath:(NSIndexPath *)indexPath {

   NSIndexPath *rowToSelect = indexPath;
   NSInteger section = indexPath.section;
   BOOL isEditing = self.editing;
   
   // If editing, don't allow instructions to be selected
   // Not editing: Only allow instructions to be selected
   if( (isEditing && section == INSTRUCTIONS_SECTION) || 
       (!isEditing && section != INSTRUCTIONS_SECTION) ) {
       [tableView deselectRowAtIndexPath:indexPath animated:YES];
       rowToSelect = nil;    
   }

   return rowToSelect;
}

/////////////////////////////////////////////////////////////
-(void)       tableView:(UITableView *)tableView 
didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
   NSInteger section = indexPath.section;
   UIViewController *nextViewController = nil;
   
   //bckong only one 1 or 2 next view controller needed
   /*
    What to do on selection depends on what section the row is in.
    For Type, Instructions, and ChapterContents, create and push a new view controller 
    of the type appropriate for the next screen.
    */
   switch(section) {
       case TYPE_SECTION:
           nextViewController = [[TypeSelectionViewController alloc] initWithStyle:
                                                                 UITableViewStyleGrouped];
           ((TypeSelectionViewController *)nextViewController).recipe = m_Chapter;
           break;
         
       case INSTRUCTIONS_SECTION:
           nextViewController = [[InstructionsViewController alloc] initWithNibName:
                                                               @"InstructionsView" bundle:nil];
           ((InstructionsViewController *)nextViewController).recipe = m_Chapter;
           break;
         
       case INGREDIENTS_SECTION:
           nextViewController = [[IngredientDetailViewController alloc] initWithStyle:
                                                                    UITableViewStyleGrouped];
           ((IngredientDetailViewController *)nextViewController).recipe = m_Chapter;
           
           if (indexPath.row < [m_Chapter.ingredients count]) {
               Ingredient *ingredient = [m_ChapterContents objectAtIndex:indexPath.row];
               ((IngredientDetailViewController *)nextViewController).ingredient = ingredient;
           }
           break;
         
       default:
           break;
   }
   
   /**
    * goto the next view
    * If we got a new view controller, push it .
    */
   if (nextViewController) {
       [self.navigationController pushViewController:nextViewController animated:YES];
       [nextViewController release];
   }
}


/////////////////////////////////////////////////////////////
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView 
          editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

   UITableViewCellEditingStyle style = UITableViewCellEditingStyleNone;
   // Only allow editing in the chapterContents section.
   // In the chapterContents section, the last row 
   // (row number equal to the count of chapterContents) is 
   // added automatically (see tableView:cellForRowAtIndexPath:) 
   // to provide an insertion cell, so configure that cell for insertion;
   // the other cells are configured for deletion.

   if (indexPath.section == INGREDIENTS_SECTION) {
       // If this is the last item, it's the insertion row.
       if (indexPath.row == [m_Chapter.ingredients count]) {
           style = UITableViewCellEditingStyleInsert;
       }
       else {
           style = UITableViewCellEditingStyleDelete;
       }
   }
   
   return style;
}

/////////////////////////////////////////////////////////////
-(void)  tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
 forRowAtIndexPath:(NSIndexPath *)indexPath {
   
   // Only allow deletion, and only in the chapterContents section
   if( (editingStyle == UITableViewCellEditingStyleDelete) && 
       (indexPath.section == INGREDIENTS_SECTION) ) {

       // Remove the corresponding ingredient object from 
       // the chapter's ingredient list and delete the appropriate table view cell.
       Ingredient *ingredient = [m_ChapterContents objectAtIndex:indexPath.row];
       [m_Chapter removeIngredientsObject:ingredient];
       [m_ChapterContents removeObject:ingredient];
       
       NSManagedObjectContext *context = ingredient.managedObjectContext;
       [context deleteObject:ingredient];
       
       [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
                             withRowAnimation:UITableViewRowAnimationTop];
   }
}



#pragma mark -
#pragma mark Moving rows
/////////////////////////////////////////////////////////////
-(BOOL)     tableView:(UITableView *)tableView 
canMoveRowAtIndexPath:(NSIndexPath *)indexPath {

   BOOL canMove = NO;
   // Moves are only allowed within the chapterContents section.  
   // Within the chapterContents section, the last row (Add Ingredient) cannot be moved.
   if (indexPath.section == INGREDIENTS_SECTION) {
       canMove = indexPath.row != [m_Chapter.ingredients count];
   }

   return canMove;
}

/////////////////////////////////////////////////////////////
-(NSIndexPath *)               tableView:(UITableView *)tableView 
targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath 
                     toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {

   NSIndexPath *target = proposedDestinationIndexPath;

   /*
    Moves are only allowed within the chapterContents section, 
    so make sure the destination is in the chapterContents section.
    If the destination is in the chapterContents section, 
    make sure that it's not the Add Ingredient row -- 
    if it is, retarget for the penultimate row.
    */
   NSUInteger proposedSection = proposedDestinationIndexPath.section;
   
   if (proposedSection < INGREDIENTS_SECTION) {
       target = [NSIndexPath indexPathForRow:0 inSection:INGREDIENTS_SECTION];
   } 
   else if (proposedSection > INGREDIENTS_SECTION) {
       target = [NSIndexPath indexPathForRow:([m_Chapter.ingredients count] - 1) inSection:INGREDIENTS_SECTION];
   } 
   else {
       NSUInteger ingredientsCount_1 = [m_Chapter.ingredients count] - 1;
       
       if (proposedDestinationIndexPath.row > ingredientsCount_1) {
           target = [NSIndexPath indexPathForRow:ingredientsCount_1 inSection:INGREDIENTS_SECTION];
       }
   }
   
   return target;
}

/////////////////////////////////////////////////////////////
-(void)  tableView:(UITableView *)tableView 
moveRowAtIndexPath:(NSIndexPath *)fromIndexPath 
       toIndexPath:(NSIndexPath *)toIndexPath {
   
   /*
    Update the chapterContents array in response to the move.
    Update the display order indexes within the range of the move.
    */
   Ingredient *ingredient = [m_ChapterContents objectAtIndex:fromIndexPath.row];
   [m_ChapterContents removeObjectAtIndex:fromIndexPath.row];
   [m_ChapterContents insertObject:ingredient atIndex:toIndexPath.row];
   
   NSInteger start = fromIndexPath.row;
   if (toIndexPath.row < start) {
      start = toIndexPath.row;
   }

   NSInteger end = toIndexPath.row;
   if (fromIndexPath.row > end) {
      end = fromIndexPath.row;
   }

   for (NSInteger i = start; i <= end; i++) {
      ingredient = [m_ChapterContents objectAtIndex:i];
      ingredient.displayOrder = [NSNumber numberWithInteger:i];
   }
}



/////////////////////////////////////////////////////////////
// ImagePickerController delegate
// 1) -(void)imagePickerController:didFinishPickingImage:editingInfo
// 2) -(void)imagePickerControllerDidCancel
/////////////////////////////////////////////////////////////
-(void)imagePickerController:(UIImagePickerController *)picker 
       didFinishPickingImage:(UIImage *)selectedImage
                 editingInfo:(NSDictionary *)editingInfo {
   
   // Delete any existing image.
   NSManagedObject *oldImage = m_Chapter.image;
   if( oldImage != nil ) {
      [m_Chapter.managedObjectContext deleteObject:oldImage];
   }
   
   // Create an image object for the new image.
   NSManagedObject *image = [NSEntityDescription 
                                insertNewObjectForEntityForName:@"Image"
                                         inManagedObjectContext:m_Chapter.managedObjectContext];

   m_Chapter.image = image;

   // Set the image for the image managed object.
   [image setValue:selectedImage 
            forKey:@"image"];
   
   // Create a thumbnail version of the image for the chapter object.
   CGSize size = selectedImage.size;
   CGFloat ratio = 0;

   if (size.width > size.height) {
      ratio = 44.0 / size.width;
   } 
   else {
      ratio = 44.0 / size.height;
   }

   CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height);
   
   UIGraphicsBeginImageContext(rect.size);
   [selectedImage drawInRect:rect];
   m_Chapter.thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   
   [self dismissModalViewControllerAnimated:YES];
}

/////////////////////////////////////////////////////////////
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
   [self dismissModalViewControllerAnimated:YES];
}

/////////////////////////////////////////////////////////////
// private method
-(void)updatePhotoButton {

   /**
    * How to present the photo button depends on the editing 
    * state and whether the chapter has a thumbnail image.
    * If the chapter has a thumbnail, set the button's highlighted 
    * state to the same as the editing state (it's highlighted if editing).
    * If the chapter doesn't have a thumbnail, then: if editing, 
    * enable the button and show an image that says "Choose Photo" or similar; 
    * if not editing then disable the button and show nothing.  
    */
   BOOL editing = self.editing;
   
   if (m_Chapter.thumbnailImage != nil) {
      [m_PhotoButton setHighlighted: editing];
   } 
   else {
      [[self photoButton] setEnabled: editing];
      
      if (editing) {
         [m_PhotoButton setImage:[UIImage imageNamed:@"choosePhoto.png"] 
                        forState:UIControlStateNormal];
      } 
      else {
         [m_PhotoButton setImage:nil forState:UIControlStateNormal];
      }
   }
}

#pragma mark -
#pragma mark dealloc
/////////////////////////////////////////////////////////////
-(void)dealloc {
   [[self tableHeaderView] release];
   [[self photoButton] release];
   [m_NameTextField release];
   [m_OverviewTextField release];
   [m_PrepTimeTextField release];
   [m_Chapter release];
   [m_ChapterContents release];
   [super dealloc];
}

@end
